<template>
  <div class="blog-home">

    <header class="top-bar" style="display: flex; align-items: center; gap: 10px;">
      <el-dropdown trigger="click" @command="handleCommand" v-if="isLoggedIn">
        <span class="el-dropdown-link" style="display: flex; align-items: center; cursor: pointer;">
          <el-avatar
              v-if="isLoggedIn && avatarUrl"
              :src="avatarUrl"
              class="custom-avatar"
          />
          <el-avatar
              v-else
              icon="el-icon-user"
              class="custom-avatar"
          />
          <span v-if="isLoggedIn" style="margin-left: 8px; font-weight: 600;">{{ nickname }}</span>
          <el-icon class="el-icon--right" style="margin-left: 4px;">
            <arrow-down />
          </el-icon>
        </span>

        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="info">个人页面</el-dropdown-item>
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-button
          v-if="!isLoggedIn"
          type="primary"
          size="small"
          @click="goLogin"
          style="margin-left: auto;"
      >
        去登录
      </el-button>
    </header>

    <p class="sub-title">最新文章列表：</p>

    <div
        v-for="post in posts"
        :key="post.id"
        class="post-card"
        @click="goPostDetail(post.id)"
    >
      <h3 class="post-title">{{ post.title }}</h3>
      <p class="post-summary">{{ post.summary || post.content.slice(0, 100) + '...' }}</p>
      <small class="post-meta">
        📅 {{ formatDate(post.createdAt) }} &nbsp;|&nbsp; 作者：{{ post.nickname }}
      </small>
    </div>

    <el-pagination
        v-if="totalPosts > pageSize"
        background
        layout="prev, pager, next"
        :page-size="pageSize"
        :total="totalPosts"
        v-model:current-page="currentPage"
        @current-change="onPageChange"
        class="pagination"
    />

    <div class="btn-group">
      <el-button type="primary" @click="goCreatePost">发布文章</el-button>
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue';
import {useRouter} from 'vue-router';
import {ElMessage} from 'element-plus';
import {ArrowDown} from '@element-plus/icons-vue'
import axios from 'axios';

const router = useRouter();

const posts = ref([]);
const currentPage = ref(1);
const totalPosts = ref(0);  // 总文章数
const pageSize = 5;

//定义展示用户信息部分
const avatarUrl = ref(localStorage.getItem('avatarUrl') || '');
const username = ref(localStorage.getItem('username') || '游客');
const nickname = ref(localStorage.getItem('nickname') || username.value);
const isLoggedIn = computed(() => !!localStorage.getItem('username')); // 判断是否已登录

// 监听 localStorage 变化（登录后更新头像和昵称）
window.addEventListener('storage', (e) => {
  if (e.key === 'avatarUrl') avatarUrl.value = e.newValue || '';
  if (e.key === 'nickname') nickname.value = e.newValue || username.value;
  if (e.key === 'username') isLoggedIn.value = !!e.newValue;
});

//退出登录
const handleCommand = (command) => {
  if (command === 'logout') {
    localStorage.clear();
    ElMessage.success('已退出登录');
    router.push('/login');
  } else if (command === 'profile') {
    router.push('/profile');
  } else if (command === 'info') {
    router.push('/info');
  }
};

function formatDate(dateStr) {
  const date = new Date(dateStr);
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
}

const fetchPosts = async (pageNum = 1) => {
  try {
    const res = await axios.get('/api/posts/page', {
      params: { pageNum, pageSize }
    });
    // 期望后端返回结构：{ data: [...], total: 100, pageNum: 1, pageSize: 5 }
    posts.value = res.data.data || [];
    totalPosts.value = res.data.total || 0;
  } catch (error) {
    ElMessage.error('获取文章列表失败');
  }
};

const onPageChange = (page) => {
  currentPage.value = page;
  fetchPosts(page);
};

const goLogin = () => {
  router.push('/login');
};

const goPostDetail = (id) => {
  router.push(`/post/${id}`);
};

const goCreatePost = () => {
  router.push('/create-post');
};

onMounted(() => {
  fetchPosts(currentPage.value);

  avatarUrl.value = localStorage.getItem('avatarUrl') || '';
  username.value = localStorage.getItem('username') || '游客';
  nickname.value = localStorage.getItem('nickname') || username.value;
});
</script>


<style scoped>
.blog-home {
  max-width: 800px;
  margin: 40px auto;
  padding: 20px;
  text-align: left;
}

.top-bar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
  font-size: 14px;
  color: #555;
  position: relative;
}

h1 {
  margin-bottom: 10px;
}

.sub-title {
  color: #888;
  margin-bottom: 20px;
}

.post-card {
  padding: 16px;
  border: 1px solid #eee;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  cursor: pointer;
  transition: box-shadow 0.2s ease, transform 0.2s ease;
  margin-bottom: 10px;
}

.post-card:hover {
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  transform: translateY(-2px);
}

.post-title {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.post-summary {
  color: #666;
  margin: 8px 0 12px;
}

.pagination {
  margin: 20px 0;
  text-align: center;
}

.btn-group {
  margin-top: 40px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.post-meta {
  color: #999;
  font-size: 12px;
}
.top-bar {
  padding: 10px 20px;
  background-color: #f5f5f5;
}
.custom-avatar {
  width: 32px;
  height: 32px;
}
.custom-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
}

.dropdown-menu li {
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.dropdown-menu li:hover {
  background-color: #409eff;
  color: white;
}
.el-dropdown-link {
  color: #555;
  font-size: 14px;
}
</style>
